﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RunAsAdministrator
{
    public class Options
    {
        public string Run { get; private set; }
        public string Dir { get; private set; }
        public string Args { get; private set; }
        public bool Env { get; private set; }
        public bool HasSwitch { get; private set; }
        public bool HasArgument { get; private set; }
        public string[] Arguments { get; private set; }

        public static Options Parse(string[] args)
        {
            var options = new Options
            {
                HasArgument = args.Any(),
                HasSwitch = args.Any(arg => arg[0] == '-'),
                Arguments = args
            };

            if (!options.HasSwitch)
            {
                return options;
            }

            for (int i = 0; i < args.Length; i++)
            {
                var arg = args[i];

                if (IsOption(arg, "env"))
                {
                    options.Env = true;
                    continue;
                }

                if (IsOption(arg, "run"))
                {
                    options.Run = GetValue(args, ref i);
                    continue;
                }
                if (IsOption(arg, "dir"))
                {
                    options.Dir = GetValue(args, ref i);
                    continue;
                }
                if (IsOption(arg, "args"))
                {
                    options.Args = GetValue(args, ref i);
                    continue;
                }
            }

            return options;
        }

        private static bool IsOption(string arg, string name)
        {
            return $"-{name}".Equals(arg, StringComparison.OrdinalIgnoreCase);
        }

        private static string GetValue(string[] args, ref int index)
        {
            if (args.Length <= index + 1)
            {
                return null;
            }
            index += 1;
            return args[index];
        }
    }
}
